package com.opensource.component.dinging;


import com.opensource.component.dinging.configuration.DingingProperties;
import com.opensource.component.dinging.message.BaseDingMessage;
import org.springframework.http.*;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import java.util.Map;

/**
 * created by zhanglong and since  2019/12/27  1:43
 *
 * @description: 描述
 */
public class DindingProvider {

    private RestTemplate restTemplate;

    private DingingProperties dingingProperties;

    public DindingProvider(RestTemplate restTemplate, DingingProperties dingingProperties) {
        this.restTemplate = restTemplate;
        this.dingingProperties = dingingProperties;
    }

    public <Msg extends BaseDingMessage> void sendMessage(Msg dingMessage){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(dingMessage.toParams(), headers);
        ResponseEntity<Void> responseEntity = restTemplate.postForEntity(dingingProperties.getDingingUrl(), entity, Void.class);
        if (responseEntity.getStatusCode() != HttpStatus.OK){
            throw new HttpClientErrorException(responseEntity.getStatusCode());
        }
    }


}
